package com.guagua.system.strategy.impl;

import com.guagua.system.entity.UploadConfig;
import com.guagua.system.strategy.UploadStrategy;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

@Component("LOCAL")
public class LocalUploadStrategy implements UploadStrategy {
    private final UploadConfig config;
    
    public LocalUploadStrategy(UploadConfig config) {
        this.config = config;
    }
    
    @Override
    public String upload(MultipartFile file) {
        try {
            String fileName = UUID.randomUUID() + getFileExtension(file);
            Path uploadPath = Paths.get(config.getLocalStoragePath(), fileName);
            Files.createDirectories(uploadPath.getParent());
            Files.copy(file.getInputStream(), uploadPath);
            return config.getLocalAccessUrl() + "/" + fileName;
        } catch (Exception e) {
            throw new RuntimeException("文件上传失败", e);
        }
    }
    
    @Override
    public void delete(String fileUrl) {
        try {
            String fileName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1);
            Path filePath = Paths.get(config.getLocalStoragePath(), fileName);
            Files.deleteIfExists(filePath);
        } catch (Exception e) {
            throw new RuntimeException("文件删除失败", e);
        }
    }
    
    private String getFileExtension(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        return originalFilename != null ? originalFilename.substring(originalFilename.lastIndexOf(".")) : "";
    }
} 